<?php

declare(strict_types=1);

namespace App\Pay\Listener;

use App\Common\Constants\Stakeholder;
use App\Order\Model\OrderModel;
use App\Order\Task\UpdateEntrustStatus;
use App\Order\Task\UpdateFreeStatus;
use App\Activity\Service\Free\FreeMiniService;
use App\Pay\Event\Notify;
use App\Pay\Service\PaidJobService;
use App\Pay\Service\PayService;
use Hyperf\DbConnection\Db;
use Hyperf\Event\Annotation\Listener;
use Psr\Container\ContainerInterface;
use Hyperf\Event\Contract\ListenerInterface;

/**
 * @Listener
 */
class NotifyListener implements ListenerInterface
{
    /**
     * @var ContainerInterface
     */
    private $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function listen(): array
    {
        return [
            Notify::class
        ];
    }

    public function process(object $event)
    {
        $data = $event->data;
        $orderNo = $data['order_no'];
        $payType = $data['pay_type'];
        $shopMemberSystem = $data['shop_member_system'];
        $container = $this->container;
        $payS = $container->get(PayService::class);
        if ($payType == Stakeholder::PAYMENT_METHOD_BALANCE){
            $msgHeader = '余额支付成功变更状态异常';
        }else{
            $msgHeader = '微信支付成功回调变更状态异常';
        }
        Db::beginTransaction();
        try {
            $orderInfo = OrderModel::query()->find($orderNo);
            if ( $orderInfo && ($orderInfo->is_pay == Stakeholder::ORDER_UNPAID) ) {
                $orderInfo->is_pay = Stakeholder::ORDER_PAID;
                $orderInfo->pay_type = $payType;
                $orderInfo->pay_no = "XP_PAY" . (int)(microtime(true) * 1000);
                $orderInfo->pay_at = date('Y-m-d H:i:s', time());
                $orderInfo->status = Stakeholder::ORDER_PENDING_PICK;
                $orderInfo->shop_member_system = $shopMemberSystem;
                $orderInfo->save();
                if ($orderInfo->order_type != Stakeholder::ORDER_TYPE_FREE){
                    //发送模板消息
                    $container->get(PayService::class)->sendPaySuccessMsg($orderInfo);
                }
                // 支付后,销量+购买数量
                // 库存-购买数量
                $container->get(PaidJobService::class)->pushChangeSaleAndStock($orderNo);
                // 是否代客单
                if ($orderInfo->platform_type == 3 and $orderInfo->entrust_phone and $orderInfo->entrust_order_id){
                    $container->get(UpdateEntrustStatus::class)->handle($orderInfo->entrust_order_id);
                }
                Db::commit();
                if ($orderInfo->order_type == Stakeholder::ORDER_TYPE_FREE){
                    $container->get(UpdateFreeStatus::class)->paymentHandle($orderInfo);
                    $container->get(FreeMiniService::class)->freeOrderStatus($orderInfo->order_no,1);
                }
                return ['code' => 1, 'msg' => 'success'];
            }else{
                $payS->writeLog('exception', $data , ['exception' => $msgHeader.'--订单不存在/重复执行']);
                return [
                    'code' => 0,
                    'throw' => $msgHeader."--订单不存在/重复执行\n".__METHOD__ . ":line:".__LINE__."\n".
                        "订单编号[向下]\n{$orderNo}\n".
                        "事件参数[向下]\n".json_encode($data)
                ];
            }

        }catch (\Exception $e){
            Db::rollBack();
            $error = $e->getMessage();
            $line = $e->getLine();
            $payS->writeLog('error', $data , ['error' => $msgHeader.'--未执行/回滚','errMsg' => $error]);
            return [
                'code' => 0,
                'throw' => $msgHeader."--未执行/回滚\n".__METHOD__ . ":line:{$line}\n".
                    "订单编号[向下]\n{$orderNo}\n".
                    "异常信息[向下]\n{$error}"
            ];
        }
    }
}
